import { t } from '@src/locales';
import echarts from 'echarts/lib/echarts';

import 'echarts/lib/component/legend';
import 'echarts/lib/component/calendar';

import 'echarts/lib/chart/scatter';
import 'echarts/lib/chart/pie';

import { formatDate } from 'pub-bbx-utils'; 

let cellSize = [64, 64];
let pieRadius = 20;
let nameMap = [t('common.base.aboutTime.sunday'), t('common.base.aboutTime.monday'), t('common.base.aboutTime.tuesday'), t('common.base.aboutTime.wednesday'), t('common.base.aboutTime.thursday'), t('common.base.aboutTime.friday'), t('common.base.aboutTime.saturday')];

class Calendar{

  constructor(){
    this.el = null;
    this.ctx = null;
    this.chart = null;
  }

  init(el, ctx){
    this.el = el;
    this.ctx = ctx;

    this.chart = echarts.init(el);
  }

  render(startDate, endDate, data = {}, totalData = {}){
    this.chart.clear();

    let start = formatDate(startDate, 'YYYY-MM-DD');
    let end = formatDate(endDate, 'YYYY-MM-DD');

    let range = [start, end];
    let days = this.getDaysOfMonth(startDate, endDate);
    // 绘制日历
    let scatter = this.getScatter(days);
    let option = this.getOption(range, scatter, (totalData.data || {}));
    this.chart.setOption(option);
    // 绘制饼图
    let pies = this.getPies(days, (data.data || []));
    this.chart.setOption({
      series: pies,
      tooltip:{
        trigger:'item',
        formatter(param){
          return `
          <div><span class="color-block" style="background-color:#03b3e2;"></span>${t('report.calendar.planCount')}：${data.data[param.seriesIndex - 1].planCount}${t('common.base.people')}</div>
          <div><span class="color-block" style="background-color:#95f204;"></span>${t('report.calendar.realCount')}：${data.data[param.seriesIndex - 1].realCount}${t('common.base.people')}</div>
          <div><span class="color-block" style="background-color:#ec808d;"></span>${t('report.calendar.effectiveCount')}${data.data[param.seriesIndex - 1].effectiveCount}${t('common.base.people')}</div>
          <div><span class="color-block" style="background-color:#c280ff;"></span>${t('report.calendar.invalidCount')}${data.data[param.seriesIndex - 1].invalidCount}${t('common.base.people')}</div>
          <div><span class="color-block" style="background-color:#5b8ff9;"></span>${t('report.calendar.workCount')}：${data.data[param.seriesIndex - 1].workCount}${t('common.base.people')}</div>
          <div><span class="color-block" style="background-color:#f6bd16;"></span>${t('report.calendar.officeCount')}${data.data[param.seriesIndex - 1].officeCount}${t('common.base.people')}</div>
          <div><span class="color-block" style="background-color:#ff99c3;"></span>${t('report.calendar.holidayCount')}：${data.data[param.seriesIndex - 1].holidayCount}${t('common.base.people')}</div>
          `
        }
      }
    })
  }

  getScatter(days){
    let data = [];
    let today = formatDate(new Date(), 'YYYY-MM-DD')

    days.forEach(day => {
      if(today == day[0]){
        data.push({
          value: day,
          label: {
            normal:{
              color: '#f00',
              fontWeight: 700
            }
          }
        })
      }else{
        data.push(day)
      }
    });

    return {
      id: 'label',
      type: 'scatter',
      coordinateSystem: 'calendar',
      symbolSize: 1,
      itemStyle: {
        normal: {
          color: 'none'
        }
      },
      label: {
        normal: {
          show: true,
          formatter(params) {
            return echarts.format.formatTime('dd', params.value[0]);
          },
          offset: [-cellSize[0] / 2 + 10, -cellSize[1] / 2 + 10],
          textStyle: {
            color: '#000',
            fontSize: 14
          }
        }
      },
      data
    }
  }

  getPies(days, dataSource){
    let chart = this.chart;

    return echarts.util.map(days, function(item, index) {
      let data = [];
      let dataItem = dataSource[index] || {}
      data.push({
        name: t('report.calendar.planCount'),
        value: dataItem.planCount || 0,
        origin:item
      })
      data.push({
        name: t('report.calendar.realCount'),
        value: dataItem.realCount || 0,
        origin:item
      })
      data.push({
        name: t('report.calendar.effectiveCount'),
        value: dataItem.effectiveCount || 0,
        origin:item
      })
      data.push({
        name: t('report.calendar.invalidCount'),
        value: dataItem.invalidCount || 0,
        origin:item
      })
      data.push({
        name: t('report.calendar.workCount'),
        value: dataItem.workCount || 0,
        origin:item
      })
      data.push({
        name: t('report.calendar.officeCount'),
        value: dataItem.officeCount || 0,
        origin:item
      })
      data.push({
        name: t('report.calendar.holidayCount'),
        value: dataItem.holidayCount || 0,
        origin:item
      })
      
      return {
        id: `${index }pie`,
        type: 'pie',
        center: chart.convertToPixel('calendar', item),
        label: {
          normal: {
            formatter: '{c}',
            position: 'inside'
          }
        },
        radius: pieRadius,
        data
      };
    });
  }

  getDaysOfMonth(startDate, endDate){
    let start = startDate.getTime();
    let end = endDate.getTime();
    let dayTime = 3600 * 24 * 1000;
    let data = [];

    for (let time = start; time <= end; time += dayTime) {
      data.push([
        echarts.format.formatTime('yyyy-MM-dd', time),
        0
      ]);
    }
    return data;
  }

  getOption(range, scatter, totalData){
    let series = [];

    if(scatter) series.push(scatter);

    return {
      legend: {
        data: [t('report.calendar.planCount'), t('report.calendar.realCount'), t('report.calendar.effectiveCount'), t('report.calendar.invalidCount'), t('report.calendar.workCount'),  t('report.calendar.officeCount'), t('report.calendar.holidayCount')],
        bottom:-5,
      },
      formatter(name) {
        switch (name){
        case t('report.calendar.planCount'):
          return `${t('report.calendar.allPlanCount')}：${totalData.planCount || 0}`;
        case t('report.calendar.realCount'):
          return `${t('report.calendar.allRealCount')}：${totalData.realCount || 0}`;
        case t('report.calendar.effectiveCount'):
          return `${t('report.calendar.allEffectiveCount')}：${totalData.effectiveCount || 0}`;
        case t('report.calendar.invalidCount'):
          return `${t('report.calendar.allInvalidCount')}：${totalData.invalidCount || 0}`;
        case t('report.calendar.workCount'):
          return `${t('report.calendar.allWorkCount')}：${totalData.workCount || 0}`;
        case t('report.calendar.officeCount'):
          return `${t('report.calendar.allOfficeCount')}：${totalData.officeCount || 0}`;
        case t('report.calendar.holidayCount'):
          return `${t('report.calendar.allHolidayCount')}：${totalData.holidayCount || 0}`;
        default:
          return `${name}`
        }
      },
      color: ['#03b3e2', '#95f204', '#ec808d', '#c280ff', '#5b8ff9', '#f6bd16', '#ff99c3'],
      calendar: {
        top: '8%',
        left: 'center',
        orient: 'vertical',
        cellSize,
        yearLabel: {
          show: false
        },
        monthLabel: {
          show: false
        },
        dayLabel: {
          textStyle: {
            fontSize: 14
          },
          margin: 10,
          firstDay: 1,
          nameMap
        },
        range
      },
      series,
    }
  }

}

export default new Calendar();